<template>
  <div>
    <div style="width: 350px; padding: 20px; margin: 0 auto; text-align: center;" id="qrcode-container">
      <img :src="qrCodeContent" alt="" style="width: 300px; height: 300px; border: 1px solid #ccc;"/>
<!--      <qrcode-vue-->
<!--        ref="qrCode"-->
<!--        :value="qrCodeContent"-->
<!--        :size="300"-->
<!--        render-as="canvas"-->
<!--      />-->
      <div>
        <div style="
        text-align: center;
        margin-top: 20px;
        font-size: 20px;
        font-weight: bold;
        color: #000;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
      ">
          <span>单位： {{ userInfo.companyName }}</span>
          <span>姓名： {{ userInfo.realName }}</span>
        </div>
      </div>
    </div>

    <el-button type="primary" style="margin-top: 20px" @click="printQrCode">
      下载二维码
    </el-button>
  </div>
</template>

<script>

import QrcodeVue from "qrcode.vue";
import html2canvas from 'html2canvas'

export default {
  name: 'qr-code-canvas',
  components: {QrcodeVue},
  props: {
    qrCodeContent: {
      type: String,
      default: ''
    },
    userInfo: {
      type: Object,
      default: () => ({})
    },
  },
  mounted() {
    // 添加二维码下方的文字
    this.$nextTick(() => {
      setTimeout(() => {
        const canvas = this.$refs.qrCode.$el.querySelector('canvas')
        if (canvas) {
          const ctx = canvas.getContext('2d')
          ctx.font = '20px Arial'
          ctx.fillStyle = '#000'
          ctx.fillText('请扫码参加考试', 10, canvas.height - 10)
        }
      }, 100) // 延时，确保二维码已绘制完成
    })
  },
  methods: {
    printQrCode() {
      // 下载图片
      this.$nextTick(() => {
        const container = document.getElementById('qrcode-container')
        html2canvas(container).then(canvas => {
          const imageUrl = canvas.toDataURL('image/png')
          const link = document.createElement('a')
          link.href = imageUrl

          // 设置下载文件名
          const {companyName, realName} = this.userInfo
          link.download = `${companyName}-${realName}-二维码.png`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        })
      })


    }
  }
}
</script>

<style scoped>


</style>

